<template>
	<view class="com-switch y-flex" :style="{
		'background-color': valueSync ? openColor : closeColor,
		'width': pixelunit(size),
		'height': rootHeight,
		'border-radius': rootHeight,
	}" @tap.stop="handleTap">
		<view class="com-switch-item y-flex y-align-center y-justify-center" :style="{
			'transform': 'translateX(' + (valueSync ? rootHeight : '0') + ')',
			'margin-top': itemMargin,
			'margin-bottom': itemMargin,
			'margin-left': itemMargin,
			'margin-right': itemMargin,
			'background-color': itemColor,
			'width': itemSize,
			'height': itemSize,
			'border-radius': itemSize,
		}">
			<slot name="open">
				<text class="com-switch-item-text" :style="{color: openColor, 'font-size': textSize}" v-if="valueSync">{{openText}}</text>
			</slot>
			<slot name="close">
				<text class="com-switch-item-text" :style="{color: closeColor, 'font-size': textSize}" v-if="!valueSync">{{closeText}}</text>
			</slot>
		</view>
	</view>
</template>

<script>
	export default {
		props: {
			disabled: {
				type: Boolean,
				default: false
			},
			value: {
				type: [Number, Boolean],
				default: 0
			},
			size: {
				type: [String, Number],
				default: 110
			},
			closeColor: {
				type: String,
				default: '#ccc'
			},
			openColor: {
				type: String,
				default: '#2ca2f9'
			},
			itemColor: {
				type: String,
				default: '#fff'
			},
			openText: {
				type: String,
				default: ''
			},
			closeText: {
				type: String,
				default: ''
			}
		},
		computed: {
			sizepx () {
				return this.unitpixel(this.size)
			},
			itemSize () {
				return ((this.sizepx / 2) - (this.sizepx / 20)) + 'px'
			},
			itemMargin () {
				return (this.sizepx / 40) + 'px'
			},
			rootHeight () {
				return (this.sizepx / 2) + 'px'
			},
			textSize () {
				return (this.sizepx / 5) + 'px'
			},
		},
		data () {
			return {
				valueSync: 0
			}
		},
		created() {
			this.valueSync = this.value
		},
		methods: {
			handleTap (e) {
				e.stopPropagation && e.stopPropagation()
				if ( this.disabled ) return
				this.valueSync = this.valueSync == 1 ? 0 : this.valueSync == 0 ? 1 : this.valueSync ? false : true
				this.$emit('input', this.valueSync)
				this.$emit('change', this.valueSync)
			},
			pixelunit (size) {
				const text = size.toString()
				return text.indexOf('px') > -1 ? text : text + 'rpx'
			},
			unitpixel (size) {
				const text = size.toString()
				return text.indexOf('rpx') > -1 ? uni.upx2px(text.replace('rpx', '')) : text.indexOf('px') > -1 ? parseFloat(text.replace('px', '')) : uni.upx2px(text)
			}
		},
		watch: {
			value (newVal) {
				this.valueSync = newVal
			}
		}
	}
</script>

<style>
	.com-switch {
		transition-property: background-color, width, height, border-radius;
		transition-duration: 300ms;
	}
	.com-switch-item {
		transition-property: transform, background-color, width, height, border-radius, margin;
		transition-duration: 300ms;
	}
</style>